package com.example.demos.service.impl;

import com.example.demos.dto.MarketAddDTO;
import com.example.demos.dto.MarketAddGoodsDTO;
import com.example.demos.dto.MarketDTO;
import com.example.demos.entity.Market;
import com.example.demos.entity.Store;
import com.example.demos.entity.Supplier;
import com.example.demos.mapper.MarketMapper;
import com.example.demos.service.MarketService;
import com.example.demos.util.PageBean;
import com.example.demos.util.PageParam;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpSession;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.time.LocalDateTime;
import java.util.List;


@Service
public class MarketServiceImpl implements MarketService {
    @Autowired
    private MarketMapper marketMapper;

    @Override
    public PageBean<List<MarketDTO>> select(String state, PageParam pageParam) {
        Page<MarketDTO> page = PageHelper.startPage(pageParam.getPage(), pageParam.getRows());
        marketMapper.select(state);
        PageBean<List<MarketDTO>> listPageBean = new PageBean<>(page.getTotal(), page.getResult());
        return listPageBean;
    }

    @Override
    public List<Supplier> selectSupplier(String type) {
        return marketMapper.selectSupplier(type);
    }

    @Override
    @Transactional
    public int insert(MarketAddDTO marketAddDTO, HttpSession session) {
        int insert = 0;
        Double total = 0.0;
        //计算总数
        for (MarketAddGoodsDTO marketDetail : marketAddDTO.getMarketDetails()) {
            if (marketDetail.getNum() == null || marketDetail.getMoney() == null)
                return -1;
            total += marketDetail.getMoney().doubleValue();
        }
        BigDecimal totalMoney = new BigDecimal(total);
        //添加market并得到marketId
        Market market = new Market();
        market.setCreater(session.getAttribute("username").toString());
        market.setCreateTime(LocalDateTime.now());
        market.setSupplierUuid(marketAddDTO.getCustomeruuid());
        market.setTotalMoney(totalMoney);
        insert = marketMapper.insertMarket(market);
        for (MarketAddGoodsDTO marketDetail : marketAddDTO.getMarketDetails()) {
            List<Store> stores = marketMapper.queryStoreId(marketDetail.getGoodsuuid());
            BigInteger storeId = null;
            if (stores == null || stores.isEmpty()) {
                storeId = null;
            } else {
                storeId = stores.get(0).getUuid();
            }
            marketMapper.insertMarketDetail(marketDetail, storeId, market.getUuid());
        }
        return insert;
    }

}

